import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { type } from "os";

export type itemType = {
  id: string;
  name: string;
  isCompleted: boolean;
};

const initialState: itemType[] = [
  { id: "1", name: "aaa", isCompleted: false },
  { id: "2", name: "bbb", isCompleted: false },
  { id: "3", name: "ccc", isCompleted: false },
];

const todoSlice = createSlice({
  name: "todoSlice",
  initialState: initialState,
  reducers: {
    addItemList(state: itemType[], action: PayloadAction<itemType>) {
      return [action.payload, ...state];
    },
    deleteList(state: itemType[], action: PayloadAction<string>) {
      return state.filter((item) => {
        return item.id != action.payload;
      });
    },
    completedList(state: itemType[], action: PayloadAction<string>) {
      const newArr = state.map((item) => {
        if (item.id == action.payload) {
          item.isCompleted = !item.isCompleted;
        }
        return item;
      });
      return newArr;
    },
  },
});

export const { addItemList, deleteList, completedList } = todoSlice.actions;

export default todoSlice.reducer;
